package com.swgk.core.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.swgk.core.R;

/**
 * Describe:可以自定义字体粗细(普通、加粗、中间值)的EditText
 * Author:  yangLei
 * Date:    2021/4/7
 */

@SuppressLint("AppCompatCustomView")
public class WSEditText extends EditText {

    float strokeWidth = 0f;

    public static final int BOLD_REGULAR = 0;
    public static final int BOLD_MEDIUM = 1;
    public static final int BOLD_BOLD = 2;

    public WSEditText(@NonNull Context context) {
        super(context);
        getStrokeWidth(null);
    }

    public WSEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        getStrokeWidth(attrs);
    }

    public WSEditText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getStrokeWidth(attrs);
    }

    private void getStrokeWidth(AttributeSet attrs) {
        if (attrs == null) {
            strokeWidth = 0.9f;
            return;
        }
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.WSEditText);
        int boldMode = ta.getInt(R.styleable.WSEditText_bold, BOLD_REGULAR);

        if (boldMode == BOLD_MEDIUM) {
            strokeWidth = 0.9f;
        } else if (boldMode == BOLD_BOLD) {
            strokeWidth = 1.5f;
        } else {
            strokeWidth = 0f;
        }
    }

    public void setBold(int boldMode) {
        if (boldMode == BOLD_MEDIUM) {
            strokeWidth = 0.9f;
        } else if (boldMode == BOLD_BOLD) {
            strokeWidth = 1.5f;
        } else {
            strokeWidth = 0f;
        }
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        Paint paint = this.getPaint();
        //设置字体描边宽度
        paint.setStrokeWidth(strokeWidth);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        super.onDraw(canvas);
    }
}
